# ------------------------------------------------------------------------------
# Creates flags for patients admitted with symptom dx
# Updates author: Cassidy Shubatt <cshubatt@gmail.com>
# To run: bash 12_disch_dx.R
# ------------------------------------------------------------------------------

# Libraries --------------------------------------------------------------------
library(here)
library(yaml)
library(tidyverse)
library(glue)

u <- modules::use(here("lib", "util.R"))

# Load data --------------------------------------------------------------------
message("Loading data...")
paths <- read_yaml(here("lib", "filepaths.yml"))
primary_dia_xwalk <- readRDS(paths$analysis$primary_dx) %>%
  mutate(dx_code_numeric = as.numeric(primary_dx_code))
overnight_lab <- ""
cohort <- readRDS(glue(paths$analysis$full_cohort)) %>%
  # select(ed_enc_id, ptid) %>%
  u$safe_left_join(primary_dia_xwalk)

# Get codes --------------------------------------------------------------------
message("Creating flags for diagnoses...")
h_codes <- c("h", "home - routine")
a_codes <- c("a", "admit")

codes_df <- cohort %>%
  mutate(
    dx_symptom = (dx_code_numeric >= 780 & dx_code_numeric < 800) |
      is.na(zc_cat_name) | (zc_cat_name == "")
  ) %>%
  mutate(dx_symptom = replace_na(dx_symptom, FALSE)) %>%
  mutate(undx_admit = dx_symptom & disch_disp %in% a_codes) %>%
  mutate(undx_home = dx_symptom & (disch_disp %in% h_codes) & !ami_day_of) %>%
  mutate(other_dx = !dx_symptom & !ami_day_of) %>%
  select(
    ed_enc_id, ptid, primary_dx_code, dx_code_numeric, dx_symptom, undx_admit,
    undx_home, other_dx
  )

# Save -------------------------------------------------------------------------
message("Saving...")
write_rds(codes_df, paths$analysis$disch_dx)

message("Done.")
